'use strict';

const db = uniCloud.database();
const uniIdCommon = require('uni-id-common');

exports.main = async (event, context) => {
  const token = context.uniIdToken || event.uniIdToken;
  if (!token) {
    return { code: 401, msg: '请先登录' };
  }
  
  const uniId = uniIdCommon.createInstance({ context });
  const tokenRes = await uniId.checkToken(token);
  if (tokenRes.code !== 0) {
    return { code: 401, msg: '登录状态已失效' };
  }
  
  const userId = tokenRes.uid;
  
  try {
    console.log('【getUserTasks】查询用户任务，userId:', userId);
    
    // 查询发布的任务
    const publishedRes = await db.collection('taskList')
      .where({ publisher_id: userId })
      .orderBy('publish_time', 'desc')
      .get();
    
    console.log('【getUserTasks】发布任务数量:', publishedRes.data.length);
    
    // 查询接单的任务 - 使用 receiver_id 字段
    const receivedRes = await db.collection('taskList')
      .where({ receiver_id: userId })
      .orderBy('publish_time', 'desc')
      .get();
    
    console.log('【getUserTasks】接单任务数量:', receivedRes.data.length);
    console.log('【getUserTasks】接单任务详情:', receivedRes.data);
    
    // 查询历史任务（已完成或已取消的发布任务）
    const historyRes = await db.collection('taskList')
      .where({
        publisher_id: userId,
        status: db.command.in(['completed', 'cancelled'])
      })
      .orderBy('publish_time', 'desc')
      .get();
    
    console.log('【getUserTasks】历史任务数量:', historyRes.data.length);
    
    return {
      code: 200,
      msg: '获取成功',
      data: {
        published: publishedRes.data,
        received: receivedRes.data,
        history: historyRes.data
      }
    };
  } catch (error) {
    return {
      code: 500,
      msg: '获取任务失败',
      error: error.message
    };
  }
};
